<script setup>
import { ref, onMounted } from 'vue'
import { Document, Upload, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 添加搜索关键词
const searchKeyword = ref('')

// 加载数据的方法
const loadData = () => {
  // 先根据关键词筛选数据
  const filteredData = searchKeyword.value
    ? tableData.value.filter(item => item.fileName.toLowerCase().includes(searchKeyword.value.toLowerCase()))
    : tableData.value

  // 再进行分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  tableData.value = filteredData.slice(start, end)
  total.value = filteredData.length
}

// 页码改变处理
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadData()
}

// 每页条数改变处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadData()
}

// 添加文件上传相关方法
const handleUploadSuccess = () => {
  ElMessage.success('上传成功')
}

// 添加搜索处理方法
const handleSearch = () => {
  currentPage.value = 1 // 重置页码到第一页
  loadData()
}

// 添加获取数据的函数
const fetchFileList = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('http://1.14.10.129:8081/system/file/list', {
      headers: {
        Authorization: token
      }
    })
    
    if (response.data.code === 200) {
      // 处理数据，添加文件类型
      const processedData = response.data.rows.map(item => ({
        ...item,
        fileType: item.fileName.split('.').pop(), // 获取文件扩展名作为文件类型
        createTime: item.createTime,
        uploadUserName: item.uploadUserName,
        id: item.id
      }))
      
      tableData.value = processedData
      total.value = response.data.total
      loadData() // 处理分页
    } else {
      ElMessage.error('获取数据失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('获取文件列表失败:', error)
    ElMessage.error('获取文件列表失败：' + error.message)
  }
}

// 修改单个文件上传处理方法
const handleSingleUpload = async (file) => {
  try {
    const token = localStorage.getItem('token')
    const formData = new FormData()
    formData.append('file', file.raw)  // 获取原始文件对象

    const response = await axios.post(
      'http://1.14.10.129:8081/system/file/upload',
      formData,
      {
        headers: {
          'Authorization': token,
          'Content-Type': 'multipart/form-data'
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('文件上传成功')
      // 刷新文件列表
      fetchFileList()
    } else {
      ElMessage.error('上传失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败：' + error.message)
  }
}

// 修改多文件上传处理方法
const handleMultiUpload = async (file, fileList) => {
  try {
    const token = localStorage.getItem('token')
    const formData = new FormData()
    
    // 使用 fileList 来获取所有选择的文件
    fileList.forEach(file => {
      formData.append('files', file.raw)
    })

    const response = await axios.post(
      'http://1.14.10.129:8081/system/file/uploads',
      formData,
      {
        headers: {
          'Authorization': token,
          'Content-Type': 'multipart/form-data'
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('文件批量上传成功')
      // 刷新文件列表
      fetchFileList()
    } else {
      ElMessage.error('上传失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败：' + error.message)
  }
}

// 添加删除文件的方法
const handleDelete = async (row) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.delete(
      `http://1.14.10.129:8081/system/file/${row.id}`,
      {
        headers: {
          Authorization: token
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      // 刷新文件列表
      fetchFileList()
    } else {
      ElMessage.error('删除失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('删除文件失败:', error)
    ElMessage.error('删除文件失败：' + error.message)
  }
}

onMounted(() => {
  fetchFileList()
})
</script>

<template>
  <div class="file-table-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文档列表</span>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索文档名称"
            style="width: 200px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="fileName" label="文档名称" min-width="200">
          <template #default="{ row }">
            <el-icon><document /></el-icon>
            <span style="margin-left: 8px">{{ row.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="文档类型" min-width="50" />
        <el-table-column prop="createTime" label="上传时间" min-width="100" />
        <el-table-column prop="uploadUserName" label="文档上传人" min-width="50" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small">查看标注数据</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除数据
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 修改上传按钮区域 -->
      <div class="upload-container">
        <!-- 修改单个文件上传按钮 -->
        <el-upload
          action="#"
          :auto-upload="false"
          :multiple="false"
          :on-change="(file) => handleSingleUpload(file)"
          :show-file-list="false"
          style="margin-right: 10px"
        >
          <el-button type="primary">
            <el-icon><upload /></el-icon>
            上传单个文档
          </el-button>
        </el-upload>

        <!-- 修改多文件上传按钮 -->
        <el-upload
          action="#"
          :auto-upload="false"
          multiple
          :on-change="(file, fileList) => handleMultiUpload(file, fileList)"
          :show-file-list="false"
        >
          <el-button type="primary">
            <el-icon><upload /></el-icon>
            上传多个文档
          </el-button>
        </el-upload>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.file-table-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

.upload-container {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: flex-start;
}
</style>
